<include file="public@header_vue"/>
<style>
    .el-pagination {
        margin-top: 20px;
    }

    .avatar {
        width: 40px;
        height: auto;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
</style>
</head>
<body>
<div id="app">
    <el-tabs type="border-card">
        <el-tab-pane label="角色管理" v-loading="onDataLoading">
            <el-row>
                <el-col :span="4" style="text-align: left">
                    <!--                    <el-button type="primary" size="mini" @click="update()">新增</el-button>-->
                </el-col>
            </el-row>
            <el-table :data="roleData"
                      row-key="id"
                      border
                      style="width: 100%;margin-bottom: 20px;">
                <el-table-column prop="id" label="ID" width="100"></el-table-column>
                <el-table-column prop="name" label="公司名称" width="150"></el-table-column>
                <el-table-column prop="url" label="角色">
                    <template slot-scope="scope">
                        <div class="custom-tree-container">
                            <el-tree
                                    :data="scope.row.list"
                                    show-checkbox
                                    node-key="id"
                                    :props="show_name"
                                    default-expand-all
                                    :expand-on-click-node="false">
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>{{ node.label }}</span>
                    <span>
<!--                      <el-button-->
                        <!--                              type="text"-->
                        <!--                              size="mini"-->
                        <!--                              @click="() => append(data)">-->
                        <!--                        新增-->
                        <!--                      </el-button>-->
                        <!--                      <el-button-->
                        <!--                              type="text"-->
                        <!--                              size="mini"-->
                        <!--                              @click="() => remove(node, data)">-->
                        <!--                        删除-->
                        <!--                      </el-button>-->
                        <el-button
                                type="text"
                                size="mini"
                                @click="() => assign_permissions(node, data)">
                        分配权限
                      </el-button>
                        <!--                        <el-button-->
                        <!--                                type="text"-->
                        <!--                                size="mini"-->
                        <!--                                @click="() => update(node, data)">-->
                        <!--                        修改-->
                        <!--                      </el-button>-->
                    </span>
                  </span>
                            </el-tree>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="create_time" label="添加时间" width="200">
                    <template slot-scope="scope">
                        {{formatDate(scope.row.create_time)}}
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination background layout="total,prev, pager, next" :total="totalNum" :page-size="10"
                           :current-page.sync="currentPage" @current-change="getData"></el-pagination>
        </el-tab-pane>
        <el-dialog :title="roleFrom.id == '' ? '新增角色' : '修改角色'" :visible.sync="dialogVisible" width="60%"
                   v-loading.fullscreen="dialogLoading">
            <el-form :model="roleFrom" class="demo-form-inline" :rules="rules" ref="roleFrom"
                     label-width="200px">
                <el-form-item label="角色名称" prop="name">
                    <el-col :span="18">
                        <el-input v-model="roleFrom.name" placeholder="角色名称"></el-input>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button v-if="roleFrom.id === ''" type="primary" @click="submit('roleFrom')">新增</el-button>
            <el-button v-else type="primary" @click="submit('roleFrom')">修改</el-button>
        </span>
        </el-dialog>
    </el-tabs>
    <el-dialog title="分配权限" :visible.sync="dialogAssignVisible" height="100%" width="100%"
               v-loading.fullscreen="dialogLoading">
        <el-tree
                :data="tableData"
                show-checkbox
                node-key="id"
                ref="tree"
                :props="show_name"
                default-expand-all
                :expand-on-click-node="false">
        </el-tree>
        <el-button @click="getCheckedNodes">确定</el-button>
    </el-dialog>
</div>
</body>
<script>
    let id = 1000;
    var app = new Vue({
        el: '#app',
        data: function () {
            var checkPhone = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('手机号不能为空'));
                } else {
                    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
                    if (reg.test(value)) {
                        callback();
                    } else {
                        return callback(new Error('请输入正确的手机号'));
                    }
                }
            };
            let self = this;
            return {
                tableData: [],
                form: {
                    keyword: '',
                },
                roleFrom: {
                    id: '',
                    name: '',
                    parent_id: '',
                },
                dialogVisible: false,
                dialogAssignVisible: false,
                dialogLoading: true,
                roleData: [],
                multipleSelection: [],
                totalNum: 0,
                currentPage: 1,
                parent_info: [],
                show_name: {
                    label: 'name'
                },
                onDataLoading: false,
                user_role_id: 0,
                headers: {'X-Requested-With': 'XMLHttpRequest'},
                rules: {
                    name: [{required: true, message: '请输入角色名称', trigger: 'blur'}]
                },
            };

        },
        created() {
            this.getData()
            this.getTableData()
        },
        methods: {
            clearForm() {
                this.form = {
                    name: '',
                }
            },
            getCheckedNodes() {
                let data = this.$refs.tree.getCheckedNodes();
                let _this = this;
                let params = {auth: data, user_role_id: _this.user_role_id}
                if (data.length > 0) {
                    axios.post("{:url('admin/role/set_user_auth')}", params, {
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                        }
                    }).then(function (response) {
                        _this.dialogLoading = false;
                        if (response.data.code === 1) {
                            _this.$message.success('设置成功');
                            _this.dialogVisible = false;
                        } else {
                            _this.$message.warning(response.data.msg);
                        }
                    }).catch(function (error) {
                        _this.dialogLoading = false;
                        _this.$message.error(error.toString())
                    })
                } else {
                    _this.$message.error('请选择设置权限')
                }

            },
            assign_permissions(node, data) {
                let _this = this;
                console.log(data)
                _this.user_role_id = data.id;
                let params = {user_role_id: data.id, company_id: data.company_id}
                axios.post("{:url('admin/role/get_user_auth')}", params, {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                    }
                }).then(function (response) {
                    _this.dialogLoading = false;
                    if (response.data.code === 1) {
                        _this.$refs.tree.setCheckedNodes(response.data.data);
                        _this.dialogVisible = false;
                    } else {
                        _this.$message.warning(response.data.msg);
                    }
                }).catch(function (error) {
                    _this.dialogLoading = false;
                    _this.$message.error(error.toString())
                })
                _this.dialogAssignVisible = true;
                _this.dialogLoading = false;

            },
            update(data) {
                let _this = this;
                if (data) {
                    _this.roleFrom = data.data
                } else {
                    _this.roleFrom = {
                        id: '',
                        name: '',
                        parent_id: '',
                    }
                }
                _this.dialogVisible = true;
                _this.dialogLoading = false;
            },
            append(data) {
                let _this = this;
                console.log(data)
                _this.dialogVisible = true;
                _this.roleFrom.parent_id = data.parent_id;
                _this.dialogLoading = false;
            },
            submit(form) {
                let _this = this;
                _this.$refs[form].validate((valid) => {
                    if (valid) {
                        axios.post("{:url('admin/role/update_role')}", this.roleFrom, {
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                            }
                        }).then(function (response) {
                            _this.dialogLoading = false;
                            if (response.data.code === 1) {
                                if (_this.roleFrom.id === '') {
                                    _this.$message.success('新增完成');
                                } else {
                                    _this.$message.success('修改成功');
                                }
                                _this.getData();
                                _this.dialogVisible = false;
                            } else {
                                _this.$message.warning(response.data.msg);
                            }
                        }).catch(function (error) {
                            _this.dialogLoading = false;
                            _this.$message.error(error.toString())
                        })
                    } else {
                        _this.dialogLoading = false;
                        return false;
                    }
                });
            },
            remove(node, data) {
                let _this = this;
                const parent = node.parent;
                const children = parent.data.children || parent.data;
                const index = children.findIndex(d => d.id === data.id);
                console.log(children[index].children)
                if (children[index].children == undefined || children[index].children.length == 0) {
                    children.splice(index, 1);
                } else {
                    _this.$message.error('该角色下还有未删除的角色');
                }
            },
            getTableData() {
                let _this = this;
                this.onDataLoading = true;
                if (this.form.keyword !== '') {
                    params.keyword = this.form.keyword;
                }
                axios.get("{:url('admin/role/oauth')}", {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                    }
                }).then(function (response) {
                    console.log(response);
                    _this.onDataLoading = false;
                    if (response.data.code === 1) {
                        _this.tableData = response.data.data;
                    } else {
                        _this.$message({
                            message: response.data.msg,
                            type: 'warning'
                        });
                    }
                }).catch(function (error) {
                    _this.onDataLoading = false;
                    _this.$message.error(error.toString())
                })
            },
            //首页获取列表数据
            getData(page = 1) {
                let _this = this;
                let params = {page: page};
                this.onDataLoading = true;
                if (this.form.keyword !== '') {
                    params.keyword = this.form.keyword;
                }
                console.log(params);
                axios.get("{:url('admin/role/index')}", {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                    params: params
                }).then(function (response) {
                    _this.onDataLoading = false;
                    if (response.data.code === 1) {
                        _this.roleData = response.data.data.data;
                        _this.totalNum = response.data.data.total;
                    } else {
                        _this.$message({
                            message: response.data.msg,
                            type: 'warning'
                        });
                    }
                }).catch(function (error) {
                    _this.onDataLoading = false;
                    _this.$message.error(error.toString())
                })
            },

            formatDate(timestamp) {
                let date = new Date(timestamp * 1000);
                return date.getFullYear() + '-' + this.prefix(date.getMonth() + 1) + '-' + this.prefix(date.getDate()) + ' ' + this.prefix(date.getHours()) + ':' + this.prefix(date.getMinutes()) + ':' + this.prefix(date.getSeconds());
            },
            prefix(num) {
                if (num < 10) {
                    return '0' + num;
                }
                return num;
            }
        }
    });
</script>
